const path = require("path");
const { join, basename } = path;
const projectRoot = join(__dirname, "../");
const getStackInfo = function () {
  // get call stack, and analyze it
  // get all file, method, and line numbers
  stackIndex = 3;
  const stacklist = new Error().stack.split("\n");

  // stack trace format:
  // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  // do not remove the regex expresses to outside of this method (due to a BUG in node.js)
  const stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi;
  const stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi;

  const s = stacklist[stackIndex] || stacklist[0];
  const sp = stackReg.exec(s) || stackReg2.exec(s);

  if (sp && sp.length === 5) {
    return {
      fileName: sp[2].replace(projectRoot, ""),
      line: sp[3],
      pos: sp[4],
      relativePath: basename(sp[2]),
      stack: stacklist.join("\n"),
    };
  }
};

module.exports = { getStackInfo };
